<?php


namespace app\common\model\mysql;


use app\common\exception\MessageException;
use think\model\concern\SoftDelete;

class DriverFile extends BaseModel
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    // 设置当前模型对应的完整数据表名称
    protected $table = 'drive_file';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 模型初始化
    protected static function init()
    {
        // TODO:初始化内容
    }

    // 文件完整路径
    public function getFilePathAttr($value, $data)
    {
        $finalUrl = $value;
        if ($data['storage'] == 1 && $value) {
            $finalUrl = config('setting.storage_prefix') . $value;
        }
        return $finalUrl;
    }

    public function getFileSizeAttr($value, $data)
    {
        $fileSize = $value;
        if ($fileSize > 1024*1024) {
            // b => kb => Mb
            $fileSize = round($fileSize / 1024 / 1024, 2); // 3.64 ;
            return $fileSize . 'M';
        }
        if ($fileSize > 1024) {
            // b => kb => Mb
            $fileSize = round($fileSize / 1024, 2); // 3.64 ;
            return $fileSize . 'K';
        }
        if ($fileSize > 0) {
            // b => kb => Mb
            $fileSize = round($fileSize, 2); // 3.64 ;
            return $fileSize . 'B';
        }
        return 0;
    }

    public static function list(array $param = [])
    {
        $order = [
            'update_time' => 'desc',
            'create_time' => 'desc',
            'id' => 'desc'
        ];

        $where = [];

        // 筛选
        if (isset($param['name'])) {
            $where[] = ['name', 'like', '%' . $param['name'] . '%'];
        }

        if (isset($param['folder_id']) && $param['folder_id'] != '') {
            $where[] = ['folder_id', '=', $param['folder_id']];
        }

        // 类型
        if (isset($param['type']) && $param['type'] != '') {
            $where[] = ['type', '=', $param['type']];
        }

        $list = self::where($where)->order($order);
        // 查询
        $count = $list->count();
        $list = $list->select();

        // halt($Model::getLastSql());
        return [
            'total' => $count,
            'list' => $list,
        ];
    }
}